package com.bjfu.intelligentrecognizeserver.controller;

import com.bjfu.intelligentrecognizeserver.common.Result;
import com.bjfu.intelligentrecognizeserver.pojo.entity.Kind;
import com.bjfu.intelligentrecognizeserver.pojo.entity.RecommendInfo;
import com.bjfu.intelligentrecognizeserver.pojo.vo.RecommendInfoVo;
import com.bjfu.intelligentrecognizeserver.service.CommonService;
import lombok.RequiredArgsConstructor;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
@RequiredArgsConstructor
public class CommonController {
    private static final Logger LOGGER = LoggerFactory.getLogger(CommonController.class);
    private final CommonService commonService;

    // 每页返回 4 条数据
    private static final int PAGE_SIZE = 4;

    @GetMapping(value = "/getRecommendInfo", produces = "application/json")
    public Result<List<RecommendInfoVo>> getRecommendInfo(@RequestParam(defaultValue = "0") int page) {
        LOGGER.info("请求第 {} 页数据", page);



        // 获取所有推荐信息
        List<RecommendInfo> allData = commonService.getRecommendInfo();
        int totalPages = (int) Math.ceil((double) allData.size() / PAGE_SIZE);

        // 检查是否超出最大页数
        if (page >= totalPages) {
            return Result.success(new ArrayList<>());
        }

        List<RecommendInfoVo> resultList = getInfoVos(page, allData);

        return Result.success(resultList);
    }

    private static @NotNull List<RecommendInfoVo> getInfoVos(int page, List<RecommendInfo> allData) {
        int startIndex = page * PAGE_SIZE;
        int endIndex = Math.min(startIndex + PAGE_SIZE, allData.size());
        // 返回分页数据
        List<RecommendInfoVo> resultList = new ArrayList<>();
        for (int i = startIndex; i < endIndex; i++) {
            RecommendInfo info = allData.get(i);
            RecommendInfoVo recommendInfoVo = new RecommendInfoVo(
                    info.getId(),info.getImageUrl(), info.getVideoUrl(), info.getDescription());
            resultList.add(recommendInfoVo);
        }
        return resultList;
    }

    @GetMapping("/getKind")
    public Result<Kind> getKind(@RequestParam Integer jieId){
        //由界去查询 门 纲 目 科 属 种
        LOGGER.info("jieId:{}",jieId);
        Kind kind = commonService.getKind(jieId);
        return Result.success(kind);
    }
}
